<?php
/**
 *生成对应XML数组
 *
 * @param string	 $comments
 * @return string
 */
function get_xml_data($data, $status = 'succ', $desc = 'OK')
{
	//
	$output = '<?xml version="1.0" encoding="utf-8"?>';
	$output .= '<root c_datetime="'. date('Y-m-d H:i:s') .'">';
	$output .= '<status>'. filter_xml_data($status) . '</status>';
	$output .= '<desc>'. filter_xml_data($desc) . '</desc>';
	$output .= array_to_xml('data', $data);
	$output .= '</root>';
	return $output;
}
/**
 *数组转换成XML
 *
 * @param string	 $comments
 * @return string
 */
function array_to_xml($name, $value)
{
	$str = '';
	if ($name = filter_xml_data($name))
	{
		// $name = str_replace('-', '', $name);
		$str  .= '<' .  $name . '>';
		if (is_array($value))
		{
			foreach($value as $k => $v)
			{
				if (is_numeric($k))
				{
					$k = $name . '_' . $k;
				}
				$str .= array_to_xml($k, $v);
			}
		}
		else
		{
			$str .= filter_xml_data($value);
		}
		$str  .= '</' .  $name . '>';
	}
	return $str;
}


/**
 *过滤xml数据
 *
 * @param string	 $comments
 * @return string
 */
function filter_xml_data($source)
{
	$source_chr = array('&', '<', '>', "'", '"', chr(10), chr(13));
	$target_chr = array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;', '', '');
	return str_replace($source_chr, $target_chr, $source);
}



/**
 * 解析xml函数
 *
 * @param string	 $comments
 * @return string
 */
function getXmlData ($strXml) {
	$pos = strpos($strXml, 'xml');
	if ($pos) {
		//$strXml = outXml($strXml);
		$xmlCode=simplexml_load_string($strXml,'SimpleXMLElement', LIBXML_NOCDATA);
		$arrayCode=get_object_vars_final($xmlCode);
		return $arrayCode ;
	} else {
		return '';
	}
}

// simplexml_load_file ( '11111.xml', 'SimpleXMLElement', LIBXML_NOCDATA );

function get_object_vars_final($obj){
	if(is_object($obj)){
		$obj=get_object_vars($obj);
	}
	if(is_array($obj)){
		foreach ($obj as $key=>$value){
			$obj[$key]=get_object_vars_final($value);
		}
	}
	return $obj;
}


//下载XML
function down_xls($data, $keynames, $name='dataxls') {
	$xls[] = "<html><meta http-equiv=content-type content=\"text/html; charset=UTF-8\"><body><table border='1'>";
	$xls[] = "<tr><td>ID</td><td>" . implode("</td><td>", array_values($keynames)) . '</td></tr>';
	foreach($data As $o) {
		$line = array(++$index);
		foreach($keynames AS $k=>$v) {
			$line[] = $o[$k];
		}
		$xls[] = '<tr><td>'. implode("</td><td>", $line) . '</td></tr>';
	}
	$xls[] = '</table></body></html>';
	$xls = join("\r\n", $xls);
	header('Content-Disposition: attachment; filename="'.$name.'.xls"');
	die(mb_convert_encoding($xls,'UTF-8','UTF-8'));
}
?>